package net.fltx.icon;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class IconDirEx {
    public char idReserved;
    public char idType;
    public char idCount;
    public List<IconDirEntryEx> idEntries=new ArrayList<IconDirEntryEx>();

    public IconDirEx(char idReserved, char idType, char idCount) {
        this.idReserved = idReserved;
        this.idType = idType;
        this.idCount = idCount;

    }

    public int sizeof(){
        return 6+idEntries.size()*16;
    }

    public byte[] toByteArray() throws IOException {
        ByteArrayOutputStream data = new ByteArrayOutputStream(sizeof());
        DataOutputStream buf = new DataOutputStream(data);
        idCount= (char) idEntries.size();

        buf.writeChar(Character.reverseBytes(idReserved));
        buf.writeChar(Character.reverseBytes(idType));
        buf.writeChar(Character.reverseBytes(idCount));
        for (int i=0;i<idEntries.size();i++){
            IconDirEntryEx idEntry=idEntries.get(i);
            if(i==0){
                idEntry.dwImageOffset=sizeof();
            }else {
                IconDirEntryEx idLast=idEntries.get(i-1);
                idEntry.dwImageOffset=idLast.dwImageOffset+idLast.dwBytesInRes;
            }
            buf.write(idEntry.toByteArray());
        }
        return data.toByteArray();
    }

}
